package com.audaque.springboot.foshanupload.security.handler;


import com.audaque.springboot.foshanupload.authcore.constants.AuthConst;
import com.audaque.springboot.foshanupload.core.result.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author zgb
 * @desc 登出成功处理器
 * @date 2022-08-05 18:08:21
 */
@Slf4j
@Component
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {
    @Autowired
    private ObjectMapper objectMapper;


    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        response.setStatus(200);


        String username  = null;
        //方法传递过来的是镜像，非null
        if (authentication != null) {
             username = authentication.getName();
        }


        //security的登出成功正是清除SecurityContext的Authentication
        Authentication authentication1 = SecurityContextHolder.getContext().getAuthentication();
        //null
        if (authentication1 != null) {
            username = authentication1.getName();
        }


        //清空security上下文
        SecurityContextHolder.clearContext();
        //登出成功处理session
        HttpSession session = request.getSession();

        session.removeAttribute(AuthConst.SESSIONID_KEY);
        //注销session
        session.invalidate();


        R r = R.ok(username + "登出成功!");

        try {
            out.write(objectMapper.writeValueAsString(r));
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }
}

